package com.wisenet.controller.web.wx;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.wisenet.controller.PlatformController;
import com.wisenet.entity.User;
import com.wisenet.service.wx.UserService;
import com.wisenet.util.encrypt.TjrAES;

@Controller
@RequestMapping("/user")
public class UserController extends PlatformController {
	@Autowired
	private UserService userService;
	
	@RequestMapping("/editUI")
	public String editUI() {
		return getBasePath() + "user";
	}
	
	/**
	 * 保存用户
	 * @param user
	 * @return 
	 * @throws Exception
	 */
	@RequestMapping("/saveUser")
	public @ResponseBody JSONObject saveUser(User user) throws Exception {
		JSONObject json = getJsonResult(user.getUsername(), user.getPassword());
		if (!json.getBooleanValue(SUCCESS)) {
			return json;
		}
		// 检查重复用户
		User existUser = userService.findByUsername(user.getUsername());
		if (existUser != null) {
			json.put(SUCCESS, false);
			json.put(MESSAGE, "用户已存在");
			return json;
		}
		int suc = userService.saveUser(user);
		if (suc < 0) {
			json.put(SUCCESS, false);
			json.put(MESSAGE, "添加失败");
		}
		return json;
	}
	
	/**
	 * 修改用户密码
	 * @param user
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/updatePassword")
	public @ResponseBody JSONObject updatePassword(User user) throws Exception {
		JSONObject json = getJsonResult(user.getUsername(), user.getPassword());
		if (!json.getBooleanValue(SUCCESS)) {
			return json;
		}
		User existUser = userService.findByUsername(user.getUsername());
		if (existUser != null) {
			existUser.setPassword(TjrAES.encrypt(user.getPassword()));
			int suc = userService.updateUser(existUser);
			if (suc < 0) {
				json.put(SUCCESS, false);
				json.put(MESSAGE, "修改失败");
			}
		}
		return json;
	}
	
	@Override
	protected String getBasePath() {
		return "/user/";
	}
	
}
